﻿using AutoMapper;
using Dapper;
using MediatR;
using MyMES.Domain.zmc;
using MyMES.Error;
using MyMES.Infrastructure.Interface;
using MyMES.Read.API.Application.Commends.Enterprises;
using MyMES.Read.API.Dtos;
using MySql.Data.MySqlClient;

namespace MyMES.Read.API.Application.CommendHandlers.Enterprises
{
    public class GetEnterpriseCommendHandlers : IRequestHandler<GetEnterpriseCommends, APIResult<List<EnterDepDto>>>
    {

        private readonly IBaseRepository<Department> depRepository;
        private readonly IBaseRepository<Enterprise> enterRepository;
        private readonly IMapper mapper;

        public GetEnterpriseCommendHandlers(IBaseRepository<Department> depRepository, IBaseRepository<Enterprise> enterRepository, IMapper mapper)
        {
            this.depRepository = depRepository;
            this.enterRepository = enterRepository;
            this.mapper = mapper;

        }




        /// <summary>
        /// 获取企业信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<APIResult<List<EnterDepDto>>> Handle(GetEnterpriseCommends request, CancellationToken cancellationToken)
        {
            try
            {
                APIResult<List<EnterDepDto>> result = new APIResult<List<EnterDepDto>>();

                result.Code = APIEnum.查询成功;
                result.Msg = "查询成功";

                var sql = " SELECT    e.*,  d.DepartmentName  FROM Enterprise e  LEFT JOIN Department d ON e.DepartmentID = d.DepartmentID  ORDER BY e.EnterpriseID ";

                var enters = await enterRepository.SelectAsync(sql);
                var deps = await depRepository.SelectAsync(sql);
                var enterDepDtos = mapper.Map<List<EnterDepDto>>(enters);
                var depDtos = mapper.Map<List<EnterDepDto>>(deps);


                foreach (var item in enterDepDtos)
                {
                    item.DepartmentName = depDtos.FirstOrDefault(x => x.DepartmentID == item.DepartmentID)?.DepartmentName;
                }

                result.data = enterDepDtos;

                return result;

            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
